package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 验证码管理
 */
@RestController
@RequestMapping("/validate")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;

    /**
     * 体检预约验证码
     * @param telephone
     * @return
     */
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone){
        Jedis resource = jedisPool.getResource();
        try {
            Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
            String code = SMSUtils.VALIDATE_CODE;
            SMSUtils.sendShortMessage(code,telephone,validateCode.toString());
            resource.setex(telephone + RedisMessageConstant.SENDTYPE_ORDER,3000,validateCode.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }finally {
            if (resource != null){
                resource.close();
            }
        }
    }

    /**
     * 手机号快速登录验证码
     * @param telephone
     * @return
     */
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){
        Jedis resource = jedisPool.getResource();
        try {
            Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
            String code = SMSUtils.VALIDATE_CODE;
            SMSUtils.sendShortMessage(code,telephone,validateCode.toString());
            resource.setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN,3000,validateCode.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }finally {
            if (resource != null){
                resource.close();
            }
        }
    }
}
